package com.vxb.testmvp.test_zonghe.test_6;

import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import com.vxb.testmvp.R;
import com.vxb.testmvp.test_zonghe.network.NetworkManager;
import com.vxb.testmvp.test_zonghe.test_3.ScoreBase;
import com.vxb.testmvp.test_zonghe.test_5.Test5Activity;
import com.vxb.testmvp.util.SPUtils;
import com.vxb.testmvp.util.Util;

import java.util.ArrayList;

import butterknife.Bind;
import butterknife.ButterKnife;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
import rx.subscriptions.CompositeSubscription;

public class Test6Activity extends AppCompatActivity {

    @Bind(R.id.recycler_view)
    RecyclerView recycler_view;

    @Bind(R.id.swipe_refresh)
    SwipeRefreshLayout swipe_refresh;

    @Bind(R.id.swipe_refresh_error)
    SwipeRefreshLayout swipe_refresh_error;

    private CompositeSubscription mCompositeSubscription;
    private LinearLayoutManager mLinearLayoutManager;

    private Test6Adapter test6Adapter;

    int mPageNum = 1;
    int zongYeShu = 0;

    private ArrayList<ScoreBase.ScoreData.ScoreContent.Detail> mData;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test6);
        ButterKnife.bind(this);
        mCompositeSubscription = new CompositeSubscription();
        initView();
        swipe_refresh.setRefreshing(true);
        initData();
    }

    private void initView() {
        mLinearLayoutManager = new LinearLayoutManager(this);
        // 初始化PullRecyclerView
        recycler_view.setLayoutManager(mLinearLayoutManager);

        test6Adapter = new Test6Adapter();
        recycler_view.setAdapter(test6Adapter);
        //  recycler_view.setHasFixedSize(true);//setHasFixedSize()方法用来使RecyclerView保持固定的大小，该信息被用于自身的优化


        swipe_refresh.setOnRefreshListener(new MyOnRefreshListener());//设置手势滑动监听器。
        swipe_refresh_error.setOnRefreshListener(new MyOnRefreshListener());//:设置手势滑动监听器。

        swipe_refresh.setColorSchemeColors(Color.BLUE, Color.GREEN, Color.RED, Color.YELLOW);//:设置进度圈的背景色。
        swipe_refresh_error.setColorSchemeColors(Color.BLUE, Color.GREEN, Color.RED, Color.YELLOW);//:设置进度圈的背景色。
        // swipe_refresh.setColorSchemeResources(int… colorResIds)//:设置进度动画的颜色。
        // swipe_refresh.setRefreshing(Boolean refreshing)//:设置组件的刷洗状态。

        recycler_view.addOnScrollListener(new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadNextPage(View view) {
                if (swipe_refresh.isRefreshing()) {
                    return;
                }
                if (test6Adapter.getFooterHolderState() == FooterState.STATE_LOADING) {
                    Log.d("@TAG", "the state is Loading, just wait..");
                    return;
                }

                if (mPageNum == 1) {
                    return;
                }

                if (mPageNum <= zongYeShu) {
                    // loading more
                    initData();
                    downOrUp = false;
                    test6Adapter.setFooterHolderState(FooterState.STATE_LOADING);
                    Log.d("TAG", "请求数据");
                } else {
                    //the end
                    test6Adapter.setFooterHolderState(FooterState.STATE_THE_END);
                }
            }
        });

    }

    boolean downOrUp = true;

    class MyOnRefreshListener implements SwipeRefreshLayout.OnRefreshListener {

        @Override
        public void onRefresh() {
            // clear()后当前的变量和所有引用到这个list的变量都指向同一个空的list，
            // 而如果你new了一个list后再赋值，则当前的变量变为一个空list，
            // 而其他以前引用到初始list的则不受影响，还是之前存有数据的list。

            if (test6Adapter.getFooterHolderState() == FooterState.STATE_LOADING) {
                return;
            }
            swipe_refresh.setRefreshing(true);
            downOrUp = true;
            mPageNum = 1;
            initData();
        }
    }

    private void setSwipeStopState() {
        swipe_refresh.setRefreshing(false);
        swipe_refresh_error.setRefreshing(false);
    }

    private void setSuccessView(boolean yesOrNo) {
        if (yesOrNo) {
            swipe_refresh.setVisibility(View.VISIBLE);
            swipe_refresh_error.setVisibility(View.GONE);
        } else {
            swipe_refresh.setVisibility(View.GONE);
            swipe_refresh_error.setVisibility(View.VISIBLE);
        }
    }

    private void initData() {
        String token = (String) SPUtils.get("token", "", this);

        mCompositeSubscription.add(NetworkManager.V2Service()
                .getScoreDetail(token, String.valueOf(mPageNum))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(
                        new Action1<ScoreBase>() {
                            @Override
                            public void call(ScoreBase scoreBase) {
                                if (downOrUp) {
                                    test6Adapter.clearData();
                                }
                                mData = (ArrayList<ScoreBase.ScoreData.ScoreContent.Detail>) scoreBase.getScoreData().getScoreContent().get(0).detailList;
                                zongYeShu = Integer.valueOf(scoreBase.scoreData.totalPage);
                                test6Adapter.addAll(mData);
                                test6Adapter.setFooterHolderState(FooterState.STATE_NORMAL);
                                mPageNum++;

                                setSwipeStopState();
                                setSuccessView(true);

                                Log.i("abcdef", "zongYeShu=" + zongYeShu);
                                Log.i("abcdef", "mPageNum=" + mPageNum);

                            }
                        },
                        new Action1<Throwable>() {
                            @Override
                            public void call(Throwable throwable) {
                                throwable.printStackTrace();
                                test6Adapter.setFooterHolderState(FooterState.STATE_NET_WORK_ERROR);
                                setSwipeStopState();
                                Util.showToast(Test6Activity.this, "网络错误,请检查网络后重试");

                                if (mPageNum == 1 && mData == null) {
                                    //说明 没数据, 第一次进入 要显示 错误页面 网络走丢了 隐藏 listview , 显示 错误界面.
                                    setSuccessView(false);
                                }
                            }
                        }));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mCompositeSubscription.hasSubscriptions()) {
            mCompositeSubscription.unsubscribe();
        }
    }

}
